package com.example.bbs.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.bbs.domain.entity.User;
import com.example.bbs.domain.model.GiteeUser;
import com.example.bbs.mapper.UserMapper;
import com.example.bbs.service.UserService;
import com.example.bbs.util.ConstantUtil;
import com.example.bbs.util.ThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate userBasicInfoRedisTemplate;


    /**
     * 根据userId获取用户信息
     * @param userId
     * @return
     */
    public User getUserByUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            log.error("参数userId 为空！");
            return null;
        }
        //优先从缓存中获取
        User user = getUserByUserIdFromCache(userId);
        if (Objects.isNull(user)) {
            //如果缓存没有，从数据库中查询
            user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUserId, userId));

            //异构入缓存
            User finalUser = user;
            ThreadPoolUtil.executorService.execute(() -> {
                userBasicInfoRedisTemplate.opsForHash().putAll(userId, User.parseEntry(finalUser));

            });
        }
        return user;
    }


    /**
     * 从缓存中获取User
     *
     * @param userId
     * @return
     */
    private User getUserByUserIdFromCache(String userId) {
        Map userEntries = userBasicInfoRedisTemplate.opsForHash().entries(userId);
        if (CollectionUtils.isEmpty(userEntries)) {
            return null;
        }
        return User.parseMap(userEntries);
    }



    /**
     * gitee登录
     *
     * @param loginUser
     * @return
     */
    public void save(GiteeUser loginUser) {
        User user = getUserByUserId(String.valueOf(loginUser.getId()));
        if (user == null) { //第一次登录，保存
            user = new User();
            user.setNickName(loginUser.getName());
            user.setAvatar(loginUser.getAvatar_url());
            user.setUserId(String.valueOf(loginUser.getId()));
            user.setType(ConstantUtil.USER_TYPE_ADMIN);
            userMapper.insert(user);
        } else {  //不是第一次登录，更新
            user.setNickName(loginUser.getName());
            user.setAvatar(loginUser.getAvatar_url());

            userMapper.updateById(user);
            userBasicInfoRedisTemplate.delete(user.getUserId());
        }

    }

    /**
     * 获取用户的权限
     *
     * @param UserId
     * @return
     */
    public Collection<? extends GrantedAuthority> getAuthority(String UserId) {
        User user = getUserByUserId(UserId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add((GrantedAuthority) () -> user.getType() == ConstantUtil.USER_TYPE_ADMIN ?
                ConstantUtil.AUTHORITY_TYPE_ADMIN : ConstantUtil.AUTHORITY_TYPE_NORMAL);
        return list;
    }



}
